package cn.yanyong.org.service.impl;

import cn.yanyong.org.basic.base.service.impl.BaseServiceImpl;
import cn.yanyong.org.basic.util.PageList;
import cn.yanyong.org.domain.Department;
import cn.yanyong.org.mapper.DepartmentMapper;
import cn.yanyong.org.query.DepartmentQuery;
import cn.yanyong.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        Long id = department.getId();
        String dirpath="";
        if(department.getParent()!=null){
            dirpath = departmentMapper.loadById(department.getParent().getId()).getDirPath();
        }
        department.setDirPath(dirpath+"/"+id);
        departmentMapper.update(department);
    }


    @Override
    public List<Department> queryTree() {
        //先查询所有数据
        List<Department> departments = departmentMapper.loadAll();
        //创建一个map集合
        Map<Long, Department> depts = new HashMap<>();
        //循环查询所有的数据
        for (Department department : departments) {
            //将查询到的数据添加到集合中
            depts.put(department.getId(),department);
        }
        // 新建一个list集合
        ArrayList<Department> first = new ArrayList<>();
        //循环查询所有的数据
        for (Department department : departments) {
            //判断，当没有父亲id就说明这是一级直接添加
            if (department.getParent_id()==null){
                first.add(department);
            }else{
                //不是一级的将自己放在上级的children中
                Department department1 = depts.get(department.getParent_id());
                if (department1!=null){
                    department1.getChildren().add(department);
                }

            }
        }
        return first;
    }
}
